package com.lo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lo.common.*;
import com.lo.dao.*;
import com.lo.entity.*;
import com.lo.server.WebSocketServer;
import com.lo.service.RecommendService;
import com.lo.service.UserService;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private RecommendService recommendService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private AvatarInfo avatarInfo;
    @Autowired
    private CertificateInfo certificateInfo;

    @Autowired
    private RedisFollowHelper redisFollowHelper;
    @Autowired
    private TextualMaterialMapper textualMaterialMapper;

    @Override
    public JsonResult login(String username, String password) {
        List<User> users = userMapper.selectByUsernameAndPassword(username,password);
        if (users.size()>1){
            throw new RuntimeException("用户名重复，查询多个用户，请联系管理员");
        }
        if (users.size()<=0){
            return new JsonResult(3,"用户名或密码错误",null);
        }
        if (users.get(0).getIsBanned()==1){
            return new JsonResult(3,"该用户已被禁用，请联系管理员解封",null);
        }
        JsonResult result =  new JsonResult(0,"学生登录成功",users.get(0));
        return result;
    }

    @Override
    public PageInfo page(int pageNum, int pageSize, Long id, String search) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> teachers = userMapper.selectByTidAndExamined(id,search);
        System.out.println(teachers);
        PageInfo pageInfo = new PageInfo(teachers);
        return pageInfo;
    }

    @Override
    public PageInfo NotExamineCoursePage(int pageNum, int pageSize, Long id, String search) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> teachers = userMapper.selectByTidAndNotExamine(id,search);
        PageInfo pageInfo = new PageInfo(teachers);
        return pageInfo;
    }

    @Override
    public JsonResult register(User user) {
        List<User> users = userMapper.selectByUsername(user.getUsername());
        if (users.size()>0 ){
            return new JsonResult(3,"用户已存在",null);
        }
        int rows = userMapper.insert(user);

        if (rows<=0){
            return new JsonResult(4,"注册失败，请联系管理员",null);
        }
        List<User> insertedUser = userMapper.selectByUsername(user.getUsername());
//        JsonResult route = recommendService.addUserRate(insertedUser.get(0).getId());//初始化用户打分表中的字段
        return new JsonResult(0,"注册成功",insertedUser.get(0));
    }

    @Override
    public JsonResult selectUserMessage(String username) {
        List<User> users = userMapper.selectByUsername(username);
        if (users.size()<=0){
            return new JsonResult(1,"查无此人，联系管理员",null);
        }
        return new JsonResult(0,"查询成功",users.get(0));
    }

    //更新用户信息和修改评论对应信息
    @Transactional
    @Override
    public JsonResult updateUserMessage(User user) {
        int rows = userMapper.updateMessage(user);
        Long commentRows = commentMapper.updateUserMessage(user);

        if (rows<=0){
            throw new RuntimeException("更新失败");
        }
        List<User> users = userMapper.selectByUsername(user.getUsername());
        return new JsonResult(0,"更新成功",users.get(0));
    }
    @Override
    public PageInfo selectAllUsers(int pageNum, int pageSize, String search) {
        PageHelper.startPage(pageNum,pageSize,search);
        List<User> users = userMapper.selectAllUsers();
        PageInfo pageInfo = new PageInfo(users);
        return pageInfo;
    }

    @Override
    public PageInfo selectAllTeachers(int pageNum, int pageSize, String search) {
        PageHelper.startPage(pageNum,pageSize,search);
        List<User> teachers = userMapper.selectAllTeachers();
        PageInfo pageInfo = new PageInfo(teachers);
        return pageInfo;
    }

    @Override
    public JsonResult setUserBanned(Long id) {
        int rows = userMapper.updateIsBanned2One(id);
        if (rows<=0){
            return new JsonResult(1,"封禁失败",null);
        }
        Message message = new Message(1,"message","账户因违规已被封禁");
        WebSocketServer.sendMessageByUserId(String.valueOf(id),message);
//        Message message = new Message();
//        message.setContent("账户因违规已被封禁");
//        message.setStatusCode(3);
//        List<Message> messages = new ArrayList<>();
//        messages.add(message);
//        ListOperations<String,Object> opsForList = redisTemplate.opsForList();
//        opsForList.rightPush("user:banned:"+id,message);
        return new JsonResult(0,"禁用成功",null);
    }

    @Override
    public JsonResult setUserEnable(Long id) {
        int rows = userMapper.updateIsBanned2Zero(id);
        if (rows<=0){
            return new JsonResult(1,"启用失败",null);
        }
        return new JsonResult(0,"启用成功",null);
    }

    @Override
    public JsonResult userCount() {
        Long count = userMapper.userCount();
        return new JsonResult(0,"用户总数",count);
    }

    @Override
    public JsonResult userOrdinaryCount() {
        return new JsonResult(0,"普通学生用户数量",userMapper.userOrdinaryCount());
    }

    @Override
    public JsonResult userVipCount() {
        return new JsonResult(0,"会员学生数量",userMapper.userVipCount());
    }

    @Override
    public JsonResult teacherCount() {
        Long count = userMapper.teacherCount();
        return new JsonResult(0,"教师总数",count);
    }

    @Override
    public JsonResult teacherOrdinaryCount() {
        return new JsonResult<>(0,"普通教师数量",userMapper.teacherOrdinaryCount());
    }

    @Override
    public JsonResult teacherVipCount() {
        return new JsonResult<>(0,"会员教师数量",userMapper.teacherVipCount());
    }

    //拒绝设置为0
    @Override
    public JsonResult refuseToTeacher(Long id) {
        Long rows = userMapper.updateIsTeacher2Zero(id);
        if (rows<=0){
            return new JsonResult(1,"更新失败，联系管理员",null);
        }
        Message message = new Message(0,"message","未通过审核，请您重新修改信息申请");
        WebSocketServer.sendMessageByUserId(String.valueOf(id),message);

//        Message message = new Message();
//        message.setContent("未通过审核，请您重新修改信息申请");
//        message.setStatusCode(0);
//        List<Message> messages = new ArrayList<>();
//        messages.add(message);
//        ListOperations<String,Object> opsForList = redisTemplate.opsForList();
//        opsForList.rightPush("user:"+id,message);
        return new JsonResult(0,"未通过教师认证审核",null);


    }
    //申请设置为1
    @Override
    public JsonResult launchToTeacher(User user) {
        Long rows = userMapper.updateIsTeacher2One(user);
        if (rows<=0){
            return new JsonResult(1,"更新失败，联系管理员",null);
        }
        return new JsonResult(0,"发起教师认证审核",null);
    }
    //通过设置为2
    @Override
    public JsonResult acceptToTeacher(Long id) {
            Long result = userMapper.updateIsTeacher2Two(id);
            List<User> users = userMapper.selectById(id);
            Long updateRows = commentMapper.updateUser2Teacher(id,users.get(0).getTrueName());
            if (result<=0 ){
                return new JsonResult(1,"教师认证失败",null);
            }
        Message message = new Message(1,"message","恭喜你已认证为学园用户,请重新登录权限解锁");
        WebSocketServer.sendMessageByUserId(String.valueOf(id),message);
            return new JsonResult(0,"恭喜你教师认证通过，请在两秒后重新登录权限解锁",users.get(0));
    }

    @Override
    public PageInfo launchingTeacher(int pageNum, int pageSize, String search) {
        PageHelper.startPage(pageNum,pageSize,search);
        List<User> users = userMapper.selectIsTeacherEOne(search);
        PageInfo pageInfo = new PageInfo(users);
        return pageInfo;
    }

    @Override
    public JsonResult signOutUser(Long id) {
        List<User> users = userMapper.selectById(id);
        if (users.get(0).getAvatarUrl()!=null && users.get(0).getAvatarUrl()!=""){
            FileDeleteUtils.delete(avatarInfo.getBasePath(),users.get(0).getAvatarUrl());
        }
        if (users.get(0).getCertificate()!=null && users.get(0).getCertificate()!=""){
            FileDeleteUtils.delete(certificateInfo.getBasePath(),users.get(0).getCertificate());
        }
        int rows = userMapper.deleteById(id);

        if (rows<=0){
            return new JsonResult(1,"删除失败,请联系管理员",null);
        }
        return new JsonResult(0,"注销成功",null);
    }

    @Override
    public JsonResult resetUserPassword(User user) {
        List<User> users = userMapper.selectByUsernameAndPhone(user.getUsername(),user.getPhone());
        if (users.size()<=0){
            return new JsonResult(3,"用户表中没有查到相关人员",null);
        }
        userMapper.updatePasswordById(users.get(0).getId(),user.getPassword());
        return new JsonResult(0,"密码修改成功",null);
    }

    @Override
    public JsonResult isFollowed(Long followId, Long userId) {
        if (!redisFollowHelper.isFollowed(followId,userId)){
            return new JsonResult(0,"未关注",false);
        }
        return new JsonResult<>(0,"已关注",true);
    }

    @Override
    public JsonResult follow(Long followId, Long userId) {
        redisFollowHelper.follow(followId,userId);
        return new JsonResult<>(0,"关注成功",followId);
    }

    @Override
    public JsonResult unFollow(Long followId, Long userId) {
        redisFollowHelper.unFollow(followId,userId);
        return new JsonResult<>(0,"取消关注成功",followId);
    }

    @Override
    public JsonResult myFollows(Long userId) {
        Boolean type = true;
        return new JsonResult<>(0,"关注列表",getFriendList(userId,redisFollowHelper.myFollows(userId),type));
    }

    @Override
    public JsonResult myFans(Long userId) {
        Boolean type=false;
        return new JsonResult<>(0,"粉丝列表",getFriendList(userId,redisFollowHelper.myFans(userId),type));
    }

    @Override
    public JsonResult myFollowCount(Long userId) {
        return new JsonResult<>(0,"关注数",redisFollowHelper.myFollowCount(userId));
    }

    @Override
    public JsonResult myFansCount(Long userId) {
        return new JsonResult<>(0,"粉丝数",redisFollowHelper.myFansCount(userId));
    }

    @Override
    public PageInfo myTextPages(int pageNum, int pageSize, Long id, String search) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> teachers = userMapper.selectTextByTidAndExamined(id,search);
        PageInfo pageInfo = new PageInfo(teachers);
        return pageInfo;

    }

    @Override
    public PageInfo myExaminingTextPages(int pageNum, int pageSize, Long id, String search) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> teachers = userMapper.selecTexttByTidAndNotExamine(id,search);
        PageInfo pageInfo = new PageInfo(teachers);
        return pageInfo;
    }

    @Override
    public JsonResult selectUserById(Long id) {
        List<User> users = userMapper.selectPersonalInfoById(id);
        if (users.size()<=0){
            return new JsonResult(1,"检索人员失败",null);
        }
        return new JsonResult(0,"人员信息",users.get(0));
    }

    @Override
    public JsonResult selectMyFollowCourse(Long userId) {
        List<CourseWithTCHName> courses = new ArrayList<>();
        List<CourseWithTCHName> textualMaterials = new ArrayList<>();
        List<CourseWithTCHName> all = new ArrayList<>();
        List<CourseWithTCHName> randomCourse = new ArrayList<>();
        List<FollowUserResp> myFollowList = (List<FollowUserResp>) myFollows(userId).getData();
        for (FollowUserResp user:myFollowList){
            System.out.println(user);
            courses = courseMapper.selectCourseByTid(user.getId());
            textualMaterials = textualMaterialMapper.selectTextByTid(user.getId());
            for (CourseWithTCHName course:courses){
                all.add(course);
            }
            for (CourseWithTCHName text:textualMaterials){
                all.add(text);
            }
        }
//        System.out.println("allcourse");
//        System.out.println(all);
        if (all.size()<=4){
            return new JsonResult<>(0,"关注课程",all);
        }

        Map<Integer,String> map = new HashMap<>();
        Random random = new Random();
        while (map.size()<4){
            Integer index = random.nextInt(Integer.valueOf(all.size()));
            if (!map.containsKey(index)){
                map.put(index,"");
                randomCourse.add(all.get(index));
            }
        }
        return new JsonResult<>(0,"关注课程",randomCourse);

    }

    //处理关注列表
    private List<FollowUserResp> getFriendList(Long userId, Set<String> friendsId,Boolean type){
        List<FollowUserResp> myFriendsList = new ArrayList<>();
        for (String entity:friendsId){
            Long id = Long.valueOf(entity);
            List<User> users = userMapper.selectById(id);
            User user = users.get(0);

            FollowUserResp followUserResp = new FollowUserResp();
            followUserResp.setId(user.getId());
            followUserResp.setUsername(user.getUsername());
            followUserResp.setAge(user.getAge());
            followUserResp.setSex(user.getSex());
            followUserResp.setVip(user.getVip());
            followUserResp.setNickname(user.getNickname());
            followUserResp.setCertificate(user.getCertificate());
            followUserResp.setAvatarUrl(user.getAvatarUrl());
            followUserResp.setIsBanned(user.getIsBanned());
            followUserResp.setIsTeacher(user.getIsTeacher());
            followUserResp.setTrueName(user.getTrueName());
            //判断是否互关
            if (type){//如果是当前userId的关注列表就判断user是否也关注了
                if (redisFollowHelper.isFollowed(userId,user.getId())){
                    followUserResp.setFollowed(true);
                }else {
                    followUserResp.setFollowed(false);
                }
            }else {//如果是当前userId粉丝列表就判断user是否被关注了
                if (redisFollowHelper.isFollowed(user.getId(),userId)){
                    followUserResp.setFollowed(true);
                }else {
                    followUserResp.setFollowed(false);
                }
            }
            myFriendsList.add(followUserResp);
        }
        return myFriendsList;
    }
}
